class MyAjax {
  constructor(url) {
    this.url = MyAjax.url(url);
  }
  static reg1 = /^http:\/\//;
  static reg2 = /^https:\/\//;
  static url(v) {
    if (!v) throw "填写地址";
    if (MyAjax.reg1.test(v) || MyAjax.reg2.test(v)) return (this.url = v);
    return (this.url = "http://" + v);
  }
  get(url, data) {
    return new Promise((resolve, reject) => {
      if (typeof url !== "string") throw "url类型错误";
      if (!MyAjax.reg1.test(url) && !MyAjax.reg2.test(url))
        url = this.url + url;
      if (data) {
        let str = "?";
        for (let key in data) {
          str += key + "=";
          str += data[key] + "&";
        }
        url += str.slice(0, str.length - 1);
      }
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status)
          return resolve(xhr.responseText);
      };
      xhr.open("GET", url);
      xhr.send();
    });
  }
  post(url, data) {
    return new Promise((resolve, reject) => {
      if (typeof url !== "string") throw "url类型错误";
      if (!MyAjax.reg1.test(url) && !MyAjax.reg2.test(url))
        url = this.url + url;
      let value;
      if (data) {
        let str = "";
        for (let key in data) {
          str += key + "=";
          str += data[key] + "&";
        }
        value = str.slice(0, str.length - 1);
      }
      const xhr = new XMLHttpRequest();
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status)
          return resolve(xhr.responseText);
      };
      xhr.open("POST", url);
      if (!(data instanceof FormData)) {
        xhr.setRequestHeader(
          "Content-type",
          "application/x-www-form-urlencoded"
        );
        xhr.send(value);
      } else {
        xhr.send(data);
      }
    });
  }
}
